package waysing.cream.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by weixin on 2016/3/6.
 */
public class HttpUtil {
    public static String SESSIONID = null;
    public static byte[] httpConnection(String urlStr) {
        byte bytes[] = null;
        // 根据地址创建URL对象(网络访问的url)
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(30000);
            conn.setConnectTimeout(30000);
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");
            if (SESSIONID != null) {    //当注销登录时 将该SESSIONID 置为空
                conn.setRequestProperty("Cookie", SESSIONID);
            }
            String cookieval = conn.getHeaderField("set-cookie");

            if (cookieval != null) {
                if ("JSESSIONID".equals(cookieval.substring(0, cookieval.indexOf("="))))
                    SESSIONID = cookieval.substring(0, cookieval.indexOf(";"));
            }
            if (200 == conn.getResponseCode()) {
                // 获取响应的输入流对象
                InputStream is = conn.getInputStream();
                //创建字节流输出对象；
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                //定义读取长度
                int lenght = 0;
                //定义缓冲区
                byte buffer[] = new byte[1024];
                //按缓冲区的大小，循环读数
                while ((lenght = is.read(buffer)) != -1) {
                    //根据读取的长度写入到os对象中
                    os.write(buffer, 0, lenght);
                }
                //释放资源
                is.close();
                os.close();
                bytes = os.toByteArray();
                //返回字符串
                String result = new String(os.toByteArray());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }
}
